<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <style>

    </style>
</head>
<body>
<form action="/TeacherLessonServlet" method="post" id="table-form">
    <input type="text" value="${id}" name="id"><br>
    <input type="text" value="${idStr}" ><br>
    <%--<input type="text" placeholder="输入sessionId" name="sid" value="${sid}"><br>--%>
    <input type="text" placeholder="输入一次性验证码" id="code" name="captcha" value="${captcha}"><br>
    <img src="/Captcha" id="captcha"/><br>
    <input type="submit" value="查询">
</form>

<br>
<br>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/captcha.js"></script>
<script src="js/code-data.js"></script>
<script>
    $("input[name=captcha]").focus();
</script>
<script>

    let recognizer = new Recognizer();

    // 加载样本数据
    for(let {char, sampleVal} of window['sample-data']) {
        recognizer.addSampleData(char, sampleVal);
    }

    (function initCaptchaRec() {
        let captcha = document.getElementById('captcha');
        if(captcha.complete === true || (captcha.complete === undefined && captcha.width !== 0)) {

            fillCaptcha();
            captcha.onload = fillCaptcha;

            function fillCaptcha() {
                let result = recognize(captcha, recognizer);
                if(typeof result !== 'string') {
                    captcha.src = '/Captcha?' + parseInt(Math.random() * 10000);
                } else {
                    document.getElementById('code').value = result;
                    if ($("input[name=id]").val() != null && $("input[name=id]").val() != "") {
                        $("#table-form").submit();
                    }
                }
            }
        } else {
            setTimeout(initCaptchaRec, 40);
        }
    })();

    function recognize(img, recognizer) {
        var imgData = getImageData(img);
        var captcha = new Captcha(imgData);

        // 处理验证码
        captcha.dispose();

        // 获取验证码中切割出的字符图形数据
        var slicedChars = captcha.sliceCharacter();

        // 不识别字符数不为4的验证码(存在粘连字符)
        if (slicedChars.length !== 4) {
            return null;
        }

        var chars = [];
        // 绘制切割出的字符图像数据
        for (var i = 0; i < slicedChars.length; i++) {
            var charImageData = slicedChars[i];

            // 将切割出的字符尺寸调整为24*24
            var normalImageData = resizeImageData(charImageData, 24, 24);

            // 使用切割出的字符图像创建Captcha实例
            var normalCaptcha = new Captcha(normalImageData);

            // 获取特征字符串
            var sampleString = normalCaptcha.getSampleString();

            // 根据特征字符串识别
            var matchedChar = recognizer.matchSample(sampleString);

            chars.push(matchedChar);
        }

        return chars.join('');
    }
</script>

</body>
